extends Node2D # 本组件继承自Node2D，用于在2D节点树中挂载

signal health_changed(current, max) # 血量变化信号，带当前血量和最大血量，方便UI等监听
signal died # 死亡信号，通知外部角色死亡
@export var max_health: int = 100 # 导出最大血量属性，可在编辑器面板设置

var current_health: int     = 100     # 当前血量，默认赋值为最大血量
var is_dead: bool           = false         # 是否已死亡的标志


func _ready():
	current_health = max_health # 初始化时将当前血量设置为最大血量


func take_damage(amount: int) -> void:
	if is_dead: # 如果已死亡，不做处理
		return
	current_health -= amount # 扣减血量
	current_health = clamp(current_health, 0, max_health) # 血量保持在0到最大血量之间
	emit_signal("health_changed", current_health, max_health) # 发出血量变化信号
	if current_health <= 0: # 若血量小于等于0，触发死亡
		die()


func heal(amount: int) -> void:
	if is_dead: # 死亡不能回血
		return
	current_health += amount # 增加血量
	current_health = clamp(current_health, 0, max_health) # 血量不超过上限
	emit_signal("health_changed", current_health, max_health) # 发出血量变化信号


func set_max_health(new_max: int) -> void:
	max_health = max(1, new_max) # 设置最大血量，最小为1
	current_health = clamp(current_health, 0, max_health) # 当前血量同步调整
	emit_signal("health_changed", current_health, max_health) # 发出血量变化信号


func get_health() -> int:
	return current_health # 返回当前血量


func get_max_health() -> int:
	return max_health # 返回最大血量


func die():
	is_dead = true # 设置为死亡
	emit_signal("died") # 发出死亡信号



func _on_hurt_component_hurt(damage:int) -> void:
	take_damage(damage)
